<template>
  <div class="outer">
    <div class="main">
      <div class="job-information">
        <div class="header">
          <div class="title">职位基本信息</div>
          <!-- <div class="exegesis">职位发布成功后，招聘类型、职位名称、职位类型、工作城市，将无法修改</div> -->
        </div>
        <div class="content">
          <div class="field job-type">
            <span>招聘类型</span>
            <div>
              <button :class="{ 'active': jobType === 'full-time' }" @click="setJobType('full-time')">社招全职</button>
              <button :class="{ 'active': jobType === 'campus-recruitment' }"
                @click="setJobType('campus-recruitment')">应届校园招聘</button>
              <button :class="{ 'active': jobType === 'internship' }" @click="setJobType('internship')">实习生招聘</button>
              <button :class="{ 'active': jobType === 'part-time' }" @click="setJobType('part-time')">兼职招聘</button>
            </div>
          </div>
          <div class="field positionName">
            <span for="title">职位名称</span>
            <el-autocomplete v-model="positionName" :fetch-suggestions="querySearchForJob" clearable
              placeholder="输入职位名称" size="large" style="margin: 5px" />
          </div>
          <div class="field job-description">
            <span for="description">职位描述</span>
            <textarea id="content" v-model="content"
              placeholder="请勿填写QQ、微信、电话等联系方式及特殊符号、性别歧视词、违反劳动法相关内容，否则有可能会导致您的账号被封禁。"></textarea>
          </div>
          <div class="field industryType">
            <span>职位类型</span>
            <el-autocomplete v-model="industryType" :fetch-suggestions="querySearchForJob" clearable
              placeholder="输入职位类型" size="large" style="margin: 5px" />
          </div>
        </div>
      </div>
      <div class="job-request">
        <div class="header">
          <div class="title">职位要求</div>
          <div class="exegesis">我们将通过以下条件，为您精选推荐合适的牛人，请尽量填写</div>
        </div>
        <div class="content">
          <div class="field experience-education">
            <span>经验和学历</span>
            <el-select id="experience" v-model="experience" placeholder="选择工作经验" style="margin-right: 20px;">
              <el-option value="不限">不限</el-option>
              <el-option value="1年以内">1年以内</el-option>
              <el-option value="1-3年">1-3年</el-option>
              <el-option value="3-5年">3-5年</el-option>
              <el-option value="5-10年">5-10年</el-option>
              <el-option value="10年以上">10年以上</el-option>
            </el-select>
            <el-select id="education" v-model="education" placeholder="选择学历">
              <el-option value="不限">不限</el-option>
              <el-option value="初中及以下">初中及以下</el-option>
              <el-option value="中专/中技">中专/中技</el-option>
              <el-option value="高中">高中</el-option>
              <el-option value="大专">大专</el-option>
              <el-option value="本科">本科</el-option>
              <el-option value="硕士">硕士</el-option>
              <el-option value="博士">博士</el-option>
            </el-select>
          </div>
          <div class="field salary" style="width: 100%;">
            <span for="title">薪资范围</span>
            <el-select v-model="minSalary" clearable placeholder="最低薪资" style="width: 140px" size="large">
              <el-option v-for="option in minSalaryOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
            <div style="color: #333; margin-left: 20px; margin-right: 20px; color: #333;">至</div>
            <el-select v-model="maxSalary" clearable placeholder="最高薪资" style="width: 140px" size="large">
              <el-option v-for="option in maxSalaryOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </div>
          <div class="field positionTagsList">
            <span for="title">职位标签</span>
            <el-tag v-for="(tag, index) in positionTagsList" :key="index" closable @close="removeTag(index)"
              style="color: #333;">{{ tag
              }}</el-tag>
            <!-- <el-input v-model="newTag" placeholder="输入新标签" style="width: 150px;" @keyup.enter="addTag">
              <template #append>
                <el-button @click="addTag" :class="{ 'active': newTag.trim() !== '' }">添加</el-button>
              </template>
</el-input> -->
            <el-select v-model="positionTagsList" multiple placeholder="请选择职位标签" style="width: 100%;">
              <el-option v-for="tag in jobTagsOptions" :key="tag.value" :label="tag.label" :value="tag.value" />
            </el-select>
          </div>
          <!-- <div class="field job-province">
            <span>工作省份</span>
            <input type="text" id="province" v-model="province" placeholder="输入工作地点">
          </div>
          <div class="field job-city">
            <span>工作城市</span>
            <input type="text" id="city" v-model="city" placeholder="输入工作城市">
          </div>
          <div class="field job-street">
            <span>工作街道</span>
            <input type="text" id="street" v-model="street" placeholder="输入工作街道">
          </div> -->

        </div>
      </div>
      <div class="time">
        <!-- <div>创建时间：{{ createTime }}</div> -->
        <div>更新时间：{{ updateTime }}</div>
      </div>
      <div class="submit">
        <button @click="clearFormAndGoBack" style="margin-right: 10px;">返回</button>
        <button @click="submitJobPostings">提交</button>
      </div>
    </div>
  </div>
</template>


<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { addjobPostings, getJobTags } from "@/api/position";
import { useUserInfor } from "@/stores/userInfo";
import { ElMessage } from 'element-plus';
import { useRouter } from "vue-router";

const router = useRouter();

const userStore = useUserInfor();



// 职位基本信息部分

// const companyName = userStore.userInfo.enterpriseName; // 公司名称
const jobType = ref("full-time"); // 招聘类型，默认为全职
const positionName = ref(""); // 职位名称
const content = ref(""); // 职位描述
const industryType = ref(""); // 职位类型

//职位要求部分
const experience = ref(""); // 经验要求
const education = ref(""); // 学历要求
const minSalary = ref(""); // 薪资范围
const maxSalary = ref(""); // 薪资范围
const positionTagsList = ref<string[]>([]);//职位标签
const jobTagsOptions = ref<any[]>([]); // 职位标签选项列表
// const newTag = ref<string>("");// 新标签的输入绑定
// const province = ref(""); // 工作省份
// const city = ref(""); // 工作城市
// const street = ref(""); // 工作街道
// const createTime = ref(new Date().toLocaleString()); // 创建时间
const updateTime = ref(new Date().toLocaleString()); // 更新时间


//招聘类型设置
const setJobType = (type: string) => {
  jobType.value = type;
};

//职位标签获取
const JobTag = async () => {
  const res = await getJobTags();
  if (res.code === 200) {
    jobTagsOptions.value = res.data.map((tag: string) => ({
      value: tag,
      label: tag,
    }));
  }
}


// 新增职位提交
const submitJobPostings = async () => {
  //是否填写
  if (!positionName.value || !content.value) {
    console.log(positionName.value);
    console.log(content.value);

    ElMessage.error("请填写完整信息！");
    return;
  } else {
    const newData = {
      companyName: userStore.userInfo.enterpriseName,
      jobType: jobType.value,
      positionName: positionName.value,
      content: content.value,
      industryType: industryType.value,
      experience: experience.value,
      education: education.value,
      positionTagsList: positionTagsList.value,
      minSalary: minSalary.value,
      maxSalary: maxSalary.value
      // province: province.value,
      // city: city.value,
      // street: street.value,
      // updateTime: updateTime.value,
    };
    const response = await addjobPostings(newData);
    if (response.code === 200) {
      console.log("新增成功！");
      //清空表单
      // companyName.value = "";
      positionName.value = "";
      content.value = "";
      industryType.value = "";
      experience.value = "";
      education.value = "";
      positionTagsList.value = [];
      // salary.value = "";
      // province.value = "";
      // city.value = "";
      // street.value = "";
      // updateTime.value = new Date().toLocaleString();
    } else {
      console.log("新增失败！");
    }
  }
}

//自动补全职位名称
interface RestaurantItem {
  value: string;
}
userStore.getJobNamesList(); // 获取学校列表

// 假设 userStore 中有 schoolList，且 schoolList 是字符串数组
// 将字符串数组转换为符合 RestaurantItem 接口的数组
const JobRestaurants = ref<RestaurantItem[]>(
  userStore.jobList.map((job) => ({ value: job }))
);

const querySearchForJob = (
  queryString: string,
  cb: (results: RestaurantItem[]) => void
) => {
  if (!JobRestaurants.value) {
    // 如果 JobRestaurants.value 是 undefined，返回空数组
    cb([]);
    return;
  }
  const results = queryString
    ? JobRestaurants.value.filter(createJobFilter(queryString))
    : JobRestaurants.value;

  // 调用回调函数返回建议列表
  cb(results);
};

const createJobFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

//薪资的控制逻辑
// 定义最小薪资的选项
const minSalaryOptions = ref([
  { label: "1k", value: "1k" },
  { label: "2k", value: "2k" },
  { label: "3k", value: "3k" },
  { label: "4k", value: "4k" },
  { label: "5k", value: "5k" },
  { label: "6k", value: "6k" },
  { label: "7k", value: "7k" },
  { label: "8k", value: "8k" },
  { label: "9k", value: "9k" },
  { label: "10k", value: "10k" },
  { label: "15k", value: "15k" },
  { label: "20k", value: "20k" },
]);
// 定义最大薪资的选项
const maxSalaryOptions = ref<RestaurantItem[]>([]);

// 监听最小薪资的变化
// 监听最小薪资的变化
watch(
  () => minSalary.value,
  //回调函数
  (newMinSalary) => {
    //newMinSalary是空值或不是有效数字
    if (!newMinSalary || isNaN(parseInt(newMinSalary.replace("k", ""), 10))) {
      maxSalaryOptions.value = [];
      maxSalary.value = "";
      return;
    }
    //转换为整数移除k
    const minSalaryValue = parseInt(newMinSalary.replace("k", ""), 10);
    const maxSalaryValue = Math.min(minSalaryValue + 5, 20); // 最大值不超过 20k

    //过滤出可用的最大薪资选项（对最大值数组中的每一个元素都执行一次测试函数）
    maxSalaryOptions.value = minSalaryOptions.value.filter((option) => {
      const optionValue = parseInt(option.value.replace("k", ""), 10);
      return optionValue > minSalaryValue && optionValue <= maxSalaryValue;
    });


    // 更新最大值的值
    if (maxSalaryOptions.value.length > 0) {
      maxSalary.value = maxSalaryOptions.value[0].value;
    } else {
      maxSalary.value = "";
    }
  }
);

onMounted(() => {
  JobTag(),
    maxSalaryOptions.value = minSalaryOptions.value.filter((option) => {
      return parseInt(option.value.replace("k", ""), 10) >= 1;
    });
});

// 添加标签
// const addTag = () => {
//   if (newTag.value.trim() !== "" && !positionTagsList.value.includes(newTag.value.trim())) {
//     positionTagsList.value.push(newTag.value.trim());
//     newTag.value = ""; // 清空输入框
//   }
// };

// 删除标签
const removeTag = (index: number) => {
  positionTagsList.value.splice(index, 1);
};

const clearFormAndGoBack = () => {
  positionName.value = "";
  content.value = "";
  industryType.value = "";
  experience.value = "";
  education.value = "";
  positionTagsList.value = [];

  router.push('/jobRecommendation')
};

</script>

<style scoped>
.outer {
  padding: 20px;
  min-height: 100vh;
}

.main {
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: auto;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 5px;
  /* background: rgba(255, 255, 255, 0.2); */
  background: rgba(89, 165, 245, 0.2);
  backdrop-filter: blur(9px);
  border-top: 1px solid #ffffff50;
  border-left: 1px solid #ffffff50;
}



.header {
  display: flex;
  flex-direction: column;
}

.header .title {
  color: #333;
  font-size: 20px;
  font-weight: bold;
  text-align: left;
}

.header .exegesis {
  font-size: 14px;
  text-align: left;
  color: #5c5c5c;
}

.content {
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  margin-left: 10%;
  margin-right: 10%;
}


.field {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 15px;
  color: #5c5c5c;
}

.field span {
  color: #333;
  width: 80px;
  margin-right: 10px;
  white-space: nowrap;
}

/* .companyName {
  color: #000;
} */


.field input,
.field textarea,
.field select {
  flex: 1;
  /* width: 100%; */
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.field textarea {
  height: 100px;
}


.job-type button {
  margin-right: 10px;
  padding: 5px 10px;
  border: transparent;
  background-color: #f0f0f0;
  cursor: pointer;
}

.job-type button.active {
  background-color: #0077C2;
  color: white;
}

.job-request {
  margin-top: 20px;
}

.time {
  text-align: right;
  font-size: 12px;
  color: #333;
}

.resp-information {
  display: flex;
  justify-content: flex-end;

}

.resPerson,
.respPos {
  height: 50px;
  line-height: 50px;
  margin-right: 10px;

}

.logo {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background-color: #ccc;
  border-radius: 50%;
  margin-right: 20px;
}

.positionTagsListbutton {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  border: 1px solid #ccc;
  border-radius: 50%;
  background-color: #333;
  cursor: pointer;
}

.positionTagsListbutton:hover {
  background-color: #f0f0f0;
}

.submit {
  margin: 20px;
  text-align: right;
}

.submit button {
  height: 50px;
  width: 60px;
  padding: 5px 10px;
  border: 1px solid #ccc;
  cursor: pointer;
}


.industryType .el-select {
  margin-left: 12px;
}

.salary .el-select {
  margin-left: 1px;
}

.el-select-dropdown__item {
  color: #000;
}

.el-select-dropdown__item:hover {
  background-color: #ccc;
}

.el-button.active {
  background-color: #0077C2;
  color: white;
}
</style>